package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"math/rand"
	"os"
	"time"
)
func main() {
	str1 := []string{"张三","李四","王五","李华","小明","哥布林"}
	dataMap:=read()
	fmt.Println(dataMap)
	//点名
	for {
		var choice string
		fmt.Print("按任意键随机选取，按q退出")
		fmt.Scanln(&choice)								//fmt.Scan(&choice)，接受数据的时候，遇到空格不算，要改成Scanln才可以识别
		if (choice =="q" || len(str1)==0){
			break
		}
		rand.Seed(time.Now().UnixNano())
		a :=rand.Intn(len(str1))
		//fmt.Println(a)
		fmt.Println("这次抽取的同学是:",str1[a])
		if dataMap[str1[a]]== 0{
			dataMap[str1[a]]=1
		}else {
			dataMap[str1[a]]=dataMap[str1[a]]+1

		}

		str1=append(str1[:a],str1[a+1:]...)
		fmt.Println("str1的长度是:",len(str1))

	}

	marshal,err :=json.Marshal(dataMap)
	if err !=nil{
		fmt.Println("转换出错")
	}else{
		fmt.Println("map转换成功")
	}
	fileName2:="作业/随机点名/随机点名.txt"
	file2,err:=os.OpenFile(fileName2,os.O_CREATE|os.O_WRONLY,os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file2.Close()
	w1:=bufio.NewWriter(file2)
	w1.WriteString(fmt.Sprintf(string(marshal)))
	w1.Flush()
}


//读取信息
func read() map[string]int{
	fileName:="作业/随机点名/随机点名.txt"
	file, err:=os.Open(fileName)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()
	//创建Reader对象
	b1:=bufio.NewReader(file)
	//1.Read(),高效读取
	p:=make([]byte,1024)
	n1,err:=b1.Read(p)
	dataMap :=make(map[string]int)
	//转为map
	err1 :=json.Unmarshal([]byte(p[:n1]),&dataMap)
	if err1 ==nil {
		fmt.Println("读取完毕。。")
		return dataMap
	}else {
		fmt.Println("读取失败",err1)
		return  make(map[string]int)
	}
}

